import os

import shutil
import uuid

from django.db.models import Max
from idna import unicode, re
from rest_framework import status
from rest_framework.response import Response

from databases.models import CommentRecord, ExperienceTypeModel, ExperienceRecord, BanNameModel, ApkVersionModel
from databases.serializers import UserInfoSerializer
from rest_api.utils.date_util import Get_Now

return_dict = {}


def get_comment(obj):
    _children = CommentRecord.objects.filter(father_id=obj.id)
    # obj.child_list = CommentRecordSerializer(_children, many=True).data
    for child in _children:
        get_comment(child)


def addExp(user_info, exp_type):
    """
    1	每日签到	5	5
    2	默认	20	5
    3	新建分享记录	12	3
    4	连续打卡7天	5	5
    5	使用智能衣	20	5
    6	发表评论	10	2
    """
    # 经验记录
    _now = Get_Now()
    _experience_type = ExperienceTypeModel.objects.get(pk=exp_type)
    try:
        _experience_record = ExperienceRecord.objects.get(user_id=user_info.id, sign_date=_now,
                                                          experience_type=_experience_type)
        if _experience_record.experience + _experience_type.incr_num <= _experience_type.day_max_num:
            # 可以增加经验值
            _experience_record.experience = _experience_type.incr_num + _experience_record.experience
            _experience_record.save()
            user_info.exp = user_info.exp + _experience_type.incr_num
            user_info.save()
            return "恭喜您，" + _experience_type.name + "获得了" + str(_experience_type.incr_num) + "积分"
        else:
            return "今日 " + _experience_type.name + " 获取积分已达上限"

    except ExperienceRecord.DoesNotExist:
        # 没有记录 新增
        _exp = ExperienceRecord()
        _exp.user = user_info
        _exp.sign_date = _now
        _exp.experience_type_id = exp_type
        _exp.experience = _experience_type.incr_num
        _exp.save()
        user_info.exp = user_info.exp + _experience_type.incr_num
        user_info.save()
        return "恭喜您，" + _experience_type.name + "获得了" + str(_experience_type.incr_num) + "积分"


def checkName(_name):
    """
    检验是否有禁止使用的名称
    如果名称不允许 则返回False
    """
    try:
        __name = "".join(re.findall(u'[\u4e00-\u9fa5]+', _name))
        if __name:
            BanNameModel.objects.get(is_delete=False, name__contains=__name)
            return False
        return True
    except BanNameModel.DoesNotExist:
        return True


def needReplaceAPK(version):
    """
    与当前最大版本进行比较 如果大于或等于数据库最大版本,进行替换
    """
    max_version = len(ApkVersionModel.objects.filter(is_delete=False, version_no__gt=version))
    if max_version:
        return False
    else:
        return True


def handle_uploaded_file(f):
    # PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
    PROJECT_ROOT = os.path.dirname(os.getcwd())
    print(PROJECT_ROOT)
    # 先写入到备份文件中
    _tmp_file_name = uuid.uuid1()
    _tmp_file_name = str(_tmp_file_name) + '.apk'
    path = os.path.join(os.path.join(os.path.join(PROJECT_ROOT, 'lucky-sport-apks'), 'history'),
                        _tmp_file_name)
    with open(path, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)
    return _tmp_file_name

def uploaded_hardware_file(f):
    """
    上传固件升级包
    """
    PROJECT_ROOT = os.path.dirname(os.getcwd())
    print(PROJECT_ROOT)
    # 先写入到备份文件中
    _tmp_file_name = uuid.uuid1()
    _tmp_file_name = str(_tmp_file_name) + '.zip'
    path = os.path.join(os.path.join(os.path.join(PROJECT_ROOT, 'lucky-sport-hardwares')),
                        _tmp_file_name)
    with open(path, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)
    return _tmp_file_name

def checkVersionMoveAPK(_version_no, _apk_url):
    try:
        # PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
        PROJECT_ROOT = os.path.dirname(os.getcwd())
        print(PROJECT_ROOT)
        from_path = os.path.join(os.path.join(os.path.join(PROJECT_ROOT, 'lucky-sport-apks'), 'history'), _apk_url)
        target_path = os.path.join(os.path.join(os.path.join(PROJECT_ROOT, 'lucky-sport-apks'), 'history'), _version_no + '.apk')
        shutil.copyfile(from_path, target_path)
    except Exception as e:
        print(e)
        return False

    # 如果比当前版本新,或者相同,进行替换 #读取操作
    if needReplaceAPK(_version_no):
        try:
            # PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
            PROJECT_ROOT = os.path.dirname(os.getcwd())
            print(PROJECT_ROOT)
            from_path = os.path.join(os.path.join(os.path.join(PROJECT_ROOT, 'lucky-sport-apks'), 'history'), _apk_url)
            target_path = os.path.join(os.path.join(PROJECT_ROOT, 'lucky-sport-apks'), 'lucky.apk')
            shutil.copyfile(from_path, target_path)
        except Exception as e:
            print(e)
            return False
    return True

def recoverAPK(_version_no):
    try:
        # PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
        PROJECT_ROOT = os.path.dirname(os.getcwd())
        print(PROJECT_ROOT)
        from_path = os.path.join(os.path.join(os.path.join(PROJECT_ROOT, 'lucky-sport-apks'), 'history'), _version_no+'.apk')
        target_path = os.path.join(os.path.join(PROJECT_ROOT, 'lucky-sport-apks'), 'lucky.apk')
        shutil.copyfile(from_path, target_path)
    except Exception as e:
        print(e)
        return False